package com.zx.练习题.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class Java性能测试 {

    private static final Map<Integer, Integer> MAP = new HashMap<>();
    private static int COUNTER = 0;

    static {
        // 初始化数据
        for (int i = 0; i < 1000; i++) {
            MAP.put(i, i);
        }
    }

    public static void main(String[] args) {
        // 1. jvm预热
        go(10);

        FutureTask<String> futureTask = new FutureTask(new Callable() {
            @Override
            public String call() throws Exception {
                go(Integer.MAX_VALUE);
                return "ok";
            }
        });
        Thread thread = new Thread(futureTask);
        thread.start();

        try {
            String s = futureTask.get(1, TimeUnit.SECONDS);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置线程标识为中断
        thread.interrupt();
        System.out.println("counter=" + COUNTER);

    }


    private static void go(int count) {
        int size = MAP.size();
        for (int i = 0; i < count; i++) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("任务退出");
                break;
            }
            for (int j = 0; j < size; j++) {
                MAP.get(i);
                COUNTER++;
            }
        }
    }

}
